package com.online.shopping.zuul;

import com.online.shopping.common.component.RestAuthenticationEntryPoin;
import com.online.shopping.common.component.RestAuthorizationHandler;
import com.online.shopping.common.filter.JwtAuthorizationFilter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		// cors：配置跨域访问
		// sessionManagement：配置session登录
		// sessionCreationPolicy：设置无状态session登录
		// 然后就是设置除了doLogin以外的请求都拦截
		// addFilterBefore：添加filter
		http.cors()
			.and()
			.sessionManagement()
			.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
			.and()
			.authorizeRequests()
			.antMatchers("/doLogin")
			.permitAll()
			.anyRequest()
			.authenticated()
			.and()
//			.addFilterBefore(new JwtAuthenticationFilter("/doLogin",authenticationManager()), UsernamePasswordAuthenticationFilter.class);   // 用户的登录认证，回调
			.addFilterBefore(new JwtAuthorizationFilter(),UsernamePasswordAuthenticationFilter.class);  // 资源的拦截认证

		// 禁用CSRF防御
		http.csrf().disable();

		// 报错的处理组件
		http.exceptionHandling().accessDeniedHandler(new RestAuthorizationHandler())
								.authenticationEntryPoint(new RestAuthenticationEntryPoin());
	}
}
